package com.example.interceptors;

import com.example.pojo.Result;
import com.example.utils.JwtUtil;
import com.example.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
//注入ioc容器
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        令牌验证 这段代码是从前端获取的token
        String token = request.getHeader("Authorization");
//        解析token
        try {
//            从redis中获取相同的token
            ValueOperations<String, String> ops = stringRedisTemplate.opsForValue();
            String redistoken = ops.get(token);
            if(redistoken==null){
//                token失效 意思就是如果前面token没存到redis中那么就会抛出错误
                throw new RuntimeException();
            }
//            claims存的解析完的
            Map<String, Object> claims = JwtUtil.parseToken(token);
//            把业务逻辑存储到Threadlocal中
            ThreadLocalUtil.set(claims);
//            放行
            return true;
        } catch (Exception e) {
//            http响应状态码为401
            response.setStatus(401);
//            不放行
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        清空threadlocal中的数据
        ThreadLocalUtil.remove();
    }
}
